import openai
import time
from config import API_KEY, API_BASE

# *******************************************************************
# 请确保这里的模型名称是您正在测试的 Embedding 模型名称
TEST_EMBEDDING_MODEL = "embedding-2" 
# *******************************************************************

print("--- Starting Embedding API Test ---")
print(f"Endpoint: {API_BASE}")
print(f"Model: {TEST_EMBEDDING_MODEL}")

try:
    # 1. 创建一个有明确超时的客户端，避免无限期等待
    # connect=10秒，read/write=30秒
    client = openai.OpenAI(
        api_key=API_KEY,
        base_url=API_BASE,
        timeout=30.0, 
    )

    # 2. 准备要发送的文本
    test_text = "这是一个用于测试向量化API的示例文本。"
    print(f"\nSending text for embedding: '{test_text}'")

    # 3. 记录时间并调用API
    start_time = time.time()
    response = client.embeddings.create(
        input=[test_text], 
        model=TEST_EMBEDDING_MODEL
    )
    end_time = time.time()

    # 4. 打印成功结果
    print("\n✅ API Call Successful!")
    print(f"Time taken: {end_time - start_time:.2f} seconds")
    
    embedding_vector = response.data[0].embedding
    print(f"Received embedding vector with {len(embedding_vector)} dimensions.")
    print(f"Vector preview: {embedding_vector[:5]}...") # 打印向量的前5个维度

except openai.Timeout as e:
    print(f"\n❌ ERROR: The request timed out after 30 seconds. {e}")
    print("This confirms a network/API responsiveness issue.")

except openai.APIStatusError as e:
    print(f"\n❌ ERROR: API returned a status error.")
    print(f"Status Code: {e.status_code}")
    print(f"Response: {e.response.text}")
    print("Check if the model name is correct and supported for embeddings.")
    
except Exception as e:
    print(f"\n❌ An unexpected error occurred: {e}")